/**
 * @class ExportSelector
 */
var ExportSelector = Class.create( {

    initialize: function() {
    		this._minPreviewHeight = "6000";
        this._maxPreviewHeight = "6000";
        var _this = this;
        var mainDiv = new Element('div', {'class': 'import-selector'});

        var _addTypeOption = function (checked, labelText, value) {
            var optionWrapper = new Element('tr');
            var input = new Element('input', {"type" : "radio", "value": value, "name": "export-type"});
            input.observe('click', _this.disableEnableOptions );
            if (checked) {
              input.checked = true;
            }
            var label = new Element('label', {'class': 'import-type-label'}).insert(input).insert(labelText);
            optionWrapper.insert(label.wrap('td'));
            return optionWrapper;
          };
        var typeListElement = new Element('table');
        typeListElement.insert(_addTypeOption(true, "图片", "image"));
        var fileDownload = new Element('a', {"id": 'downloadLink', "style": 'display:none'});
        mainDiv.insert(fileDownload);
        var promptType = new Element('div', {'class': 'import-section'}).update("导出类型:");
        var dataSection2 = new Element('div', {'class': 'import-block'});
        dataSection2.insert(promptType).insert(typeListElement);
        mainDiv.insert(dataSection2);

        var _addConfigOption = function (checked, name, cssClass, labelText, value) {
            var optionWrapper = new Element('tr');
            var input = new Element('input', {"type" : "radio", "value": value, "name": name });
            if (checked) {
              input.checked = true;
            }
            var label = new Element('label', {'class': cssClass}).insert(input).insert(labelText);
            optionWrapper.insert(label.wrap('td'));
            return optionWrapper;
          };
        var configListElementJSON = new Element('table', {"id": "jsonOptions", "style": 'display:none'});
        configListElementJSON.insert(_addConfigOption(true,  "export-options", "import-config-label", "导出全部数据项", "all"));
        configListElementJSON.insert(_addConfigOption(false, "export-options", "import-config-label", "删除个人信息 (用户名 和 年龄)", "nopersonal"));
        configListElementJSON.insert(_addConfigOption(false, "export-options", "import-config-label", "删除个人信息和备注", "minimal"));

        var configListElementPED = new Element('table', {"id": "pedOptions"});
//      var label = new Element('label', {'class': 'export-config-header'}).insert("下列哪个字段应该用来生成家系图成员ID?");
//      configListElementPED.insert(label.wrap('td').wrap('tr'));
//      configListElementPED.insert(_addConfigOption(false,  "ped-options", "export-subconfig-label", "家系ID", "external"));
//      configListElementPED.insert(_addConfigOption(false, "ped-options", "export-subconfig-label", "姓名", "name"));
//      configListElementPED.insert(_addConfigOption(false, "ped-options", "export-subconfig-label", "没有，为每个人生成新的数字id", "newid"));
	
		//家系图导出图片
		var configListElementImage = new Element('table', {"id": "imageOptions",});
       configListElementImage.insert(_addConfigOption(true, "image-options", "export-subconfig-label", "SVG格式", "svg"));
       configListElementImage.insert(_addConfigOption(false, "image-options", "export-subconfig-label", "PNG格式", "png"));     
            
        var promptConfig = new Element('div', {'class': 'import-section'}).update("设置选项:");
        var dataSection3 = new Element('div', {'class': 'import-block'});
        dataSection3.insert(promptConfig).insert(configListElementImage);
        mainDiv.insert(dataSection3);

        var buttons = new Element('div', {'class' : 'buttons import-block-bottom'});
        buttons.insert(new Element('input', {type: 'button', name : 'export', 'value': '导出', 'class' : 'button', 'id': 'export_button'}).wrap('span', {'class' : 'buttonwrapper'}));
        buttons.insert(new Element('input', {type: 'button', name : 'cancel', 'value': '撤销', 'class' : 'button secondary'}).wrap('span', {'class' : 'buttonwrapper'}));
        mainDiv.insert(buttons);

        var cancelButton = buttons.down('input[name="cancel"]');
        cancelButton.observe('click', function(event) {
            _this.hide();
        })
        var exportButton = buttons.down('input[name="export"]');
        exportButton.observe('click', function(event) {
            _this._onExportStarted();
        })

        var closeShortcut = ['Esc'];
        this.dialog = new PhenoTips.widgets.ModalPopup(mainDiv, {close: {method : this.hide.bind(this), keys : closeShortcut}}, {extraClassName: "pedigree-import-chooser", title: "家系图导出", displayCloseButton: true});
        //Event.observe(window, 'resize', adjustPreviewWindowHeight.bind(_this, "pedigree-import-chooser", 'scrollable-container', this._minPreviewHeight, this._maxPreviewHeight));
    },

  
    disableEnableOptions: function() {
        var exportType = $$('input:checked[type=radio][name="export-type"]')[0].value;

        var pedOptionsTable = $("pedOptions");
        var jsonOptionsTable = $("jsonOptions");
        var imageOptionsTable = $("imageOptions");
        imageOptionsTable.show();

//      if (exportType == "ped" || exportType == "BOADICEA") {
//          pedOptionsTable.show();
//          jsonOptionsTable.hide();
//          imageOptionsTable.hide();
//      } else {
//              pedOptionsTable.hide();
//
//              if (exportType == "simpleJSON") {
////                  jsonOptionsTable.show();
//                  imageOptionsTable.show();
//              } else {
////                  jsonOptionsTable.hide();
//                  imageOptionsTable.show();
//              }
//     	}
        //adjustPreviewWindowHeight('pedigree-import-chooser', 'scrollable-container', this._minPreviewHeight, this._maxPreviewHeight);
    
    },

    /**
     *
     * @param event
     * @param pictureBox
     * @private
     */
    _onExportStarted: function() {
        var patientDocument = XWiki.currentDocument.page + "familytree";

        var exportType = $$('input:checked[type=radio][name="export-type"]')[0].value;
        if (exportType == "image") {
                var imageType = $$('input:checked[type=radio][name="image-options"]')[0].value;

                var _bbox = $('canvas').down().getBBox();
                var svgEl = $$("#canvas svg")[0];
                var background = $$('.panning-background')[0];
                svgEl.insertBefore(new Element('rect', {"id": "white-bbox-background",
                                                        "width": _bbox.width,
                                                        "height": _bbox.height,
                                                        "x": _bbox.x,
                                                        "y": _bbox.y,
                                                        "fill": "white"}),
                                   svgEl.firstChild
                );

                var svg = editor.getWorkspace().getSVGCopy();
                var exportString = svg.getSVGText();
                $('white-bbox-background').remove();
                if (imageType == "png") {
                    debugger;
                    var canversWidth = _bbox.width;
                    var canversHeight = _bbox.height;
                    var svgXml = svg.getSVGText();     
                    var image = new Image();
                    image.setAttribute('crossOrigin', 'Anonymous');
                    image.onload = null;
                    var desImage = new Image();
                    desImage.setAttribute('crossOrigin', 'Anonymous');
                    desImage.onload = null;
                    desImage.src = "/static/familyTree/image/four.jpg";
                    image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgXml))); //给图片对象写入base64编码的svg流	
                    var canvas = document.createElement('canvas');  //准备空画布
                    canvas.width = canversWidth+400;
                    canvas.height = canversHeight+100;
                    var context = canvas.getContext('2d');  //取得画布的2d绘图上下文
                    context.fillStyle = "#fff";
                    //var _this = this;
                    image.onload=function(){
                        var imgWidth = image.width;
                        var imageHeight = image.height;
                        context.fillRect(0, 0, canvas.width, canvas.height);
                        context.drawImage(image, 0, 0,imgWidth,imageHeight);
                        if((desImage.width > 0 && desImage.height > 0)){
                            var desImgWidth = desImage.width;
                            var desImageHeight = desImage.height;
                            context.drawImage(desImage, canvas.width-400, 0,desImgWidth,desImageHeight);
                            var a = document.createElement('a');
                            a.href = canvas.toDataURL('image/png');  //将画布内的信息导出为png图片数据
                            a.setAttribute("download",new Date().getTime()+'.png');
                            document.body.appendChild(a);
                            a.click(); //点击触发下载
                            a.remove();
                            return;
                        }
                        desImage.onload = function(){
                            var desImgWidth = desImage.width;
                            var desImageHeight = desImage.height;
                            context.drawImage(desImage, canvas.width-400, 0,desImgWidth,desImageHeight);
                            var a = document.createElement('a');
                            a.href = canvas.toDataURL('image/png');  //将画布内的信息导出为png图片数据
                            a.setAttribute("download",new Date().getTime());
                            document.body.appendChild(a);
                            a.click(); //点击触发下载
                            a.remove();
                            return;
                        };
                         desImage.onerror = function(error){
                             console.log(error);
                         }
                    };
                    image.onerror = function(error){
                        console.log(error);
                    }
                } else {
                     var fileName = patientDocument + ".svg";
                }
        } else if (exportType == "simpleJSON") {
            var privacySetting = $$('input:checked[type=radio][name="export-options"]')[0].value;
            var exportString = PedigreeExport.exportAsSimpleJSON(editor.getGraph().DG, privacySetting);
            var fileName = patientDocument + ".json";
            var mimeType = "application/json";
        } else {
            var idGenerationSetting = $$('input:checked[type=radio][name="ped-options"]')[0].value;
            if (exportType == "ped") {
                var exportString = PedigreeExport.exportAsPED(editor.getGraph().DG, idGenerationSetting);
                var fileName = patientDocument + ".ped";
            } else if (exportType == "BOADICEA") {
                var exportString = PedigreeExport.exportAsBOADICEA(editor.getGraph().DG, idGenerationSetting);
                var fileName = patientDocument + ".dat";
            }
            var mimeType = "text/plain";
        }
        //添加四项线 chen.yuguo start
        var regex = /<svg.*?>/ig; 
        while((result= regex.exec(exportString))!=null)
            svg_ret = result[0];
        if(svg_ret){
            var width = /width="([^\"]*)"/ig;
            var viewbox = /viewBox="([^\"]*)"/ig;
            while((result= viewbox.exec(svg_ret))!=null){
                 svg_width_back = result[1];
                 svg_width_back = svg_width_back.split(' ');
                 svg_width_back_1 = parseInt(svg_width_back[0]);
                 svg_width_back_2 = parseInt(svg_width_back[2]);
                 svg_width_back1 = svg_width_back_2+svg_width_back_1;
             }
            while((result= width.exec(svg_ret))!=null){
                 svg_width = result[1];
             }
            var height = /height="([^\"]*)"/ig;
            while((result= height.exec(svg_ret))!=null)
                 svg_height = result[1];
            if(svg_height && svg_width){
                width1 = parseInt(svg_width)+600;
                height1 = parseInt(svg_height);
            }
            var regex1 = /<rect[^\>]*?>/ig; 
            result1= regex1.exec(exportString);
            if(result1[0]){
                var pre_width = /width="([^\"]*)"/ig;
                ret_width = result1[0];
                while((result= pre_width.exec(ret_width))!=null){
                     ret_width1 = result[1];
                 }
                str_ret1 = result1[0].replace(/width="[^\"]*"/ig,'width="'+(parseFloat(ret_width1)+600)+'"');
                exportString = exportString.replace(result1[0],str_ret1);
                //console.log(result1[0],str_ret1,ret_width1);return false;
            }
            svg_ret1 = svg_ret.replace(/width="[^\"]*"/ig,'width="'+width1+'"');
            //console.log(svg_ret,svg_ret1);return false;
            exportString = exportString.replace(svg_ret,svg_ret1);
            if(svg_width_back){
                var svg_width_back_1_back = Math.abs(svg_width_back_1);
                if(svg_width_back_1_back!=svg_width_back_1){
                   svg_width = svg_width_back1;
                }
            }
            exportString = exportString.replace('</svg>','<image xlink:href="http://www.familytree-med.com/images/common/four1.jpg" x="'+(parseInt(svg_width)+100)+'" y="'+(parseInt(svg_width_back[1])+100)+'" width="400" height="310" x1="'+svg_width+'" x2="'+width1+'" /></svg>');
            console.log(svg_ret1+'------');
            
        }
        //添加四项线 chen.yuguo end
        //console.log("Export data: >>" + exportString + "<<");
        
        sessionStorage.setItem("exportJSONDATA",exportString);
        		if (exportString != "") {
                if (exportType != "image") {
                    saveTextFile(exportString, fileName);
                } else if (exportType == "image" && imageType == "svg") {
                    saveSVGFile(exportString, fileName);
                }
            }
        	this.hide();
    },

    /**
     *
     * @method show
     */
    show: function() {
        this.dialog.show();
        //adjustPreviewWindowHeight('pedigree-import-chooser', 'scrollable-container', this._minPreviewHeight, this._maxPreviewHeight);
    },

    /**
     *
     * @method hide
     */
    hide: function() {
        this.dialog.closeDialog();
    }
});